package com.lss.loginregister.fragment;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.lss.loginregister.R;
import com.lss.loginregister.databinding.FragmentDataTransmitBinding;
import com.lss.loginregister.entity.Person;
import com.lss.loginregister.viewmodel.DataTransmitViewModel;

public class DataTransmitFragment extends Fragment {
    private FragmentDataTransmitBinding binding;
    private DataTransmitViewModel viewModel;

    public static DataTransmitFragment newInstance() {
        return new DataTransmitFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_data_transmit, container, false);
        viewModel = new ViewModelProvider(this).get(DataTransmitViewModel.class);
        binding.setVm(viewModel);
        binding.setPerson(new Person());
        // 设置生命周期所有者
        binding.setLifecycleOwner(getViewLifecycleOwner());
        // 观察提交状态
        viewModel.getSubmitSuccess().observe(getViewLifecycleOwner(), success -> {
            if (success) {
                // 提交成功处理
                onSubmitSuccess();
            }
        });

        return binding.getRoot();
    }
    // 提交成功后的处理
    private void onSubmitSuccess() {
        // 显示成功提示
        Toast.makeText(requireContext(), "提交成功", Toast.LENGTH_SHORT).show();
        // 清空表单
        binding.setPerson(new Person());
        // 清除错误状态
        viewModel.ageError.set(null);

        // 可选：导航到其他界面
        // findNavController().navigate(R.id.action_dataTransmitFragment_to_nextFragment);
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewModel = new ViewModelProvider(this).get(DataTransmitViewModel.class);
        // TODO: Use the ViewModel
    }

}